package cn.pconline.autoclub.service;

import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.SqlBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import cn.pconline.autoclub.entity.DailyGeneralSituation;
import cn.pconline.autoclub.util.Pager;
import java.util.Map;
import org.gelivable.dao.SqlPageBuilder;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 
 * @author zhoutianhuai
 *
 */
public class DailyGeneralSituationService {
	  @Autowired
	  private GeliOrm geliOrm;
	  @Autowired
	  private GeliDao geliDao;
	  @Autowired
	  private PagerService pagerService;
	  @Autowired
	  private SqlPageBuilder pageBuilder;
	  /**
	   * 分页查询某个时间段车友会总体情况
	   * @return
	   */
	  public Pager<DailyGeneralSituation> getDailyGeneralSituationForPage(int beginDate, int endDate, int pageNo, int pageSize){
		  SqlBuilder sql = new SqlBuilder();
		  sql.appendSql(" select belongs_date from ").appendSql(geliOrm.getTableName(DailyGeneralSituation.class));
		  sql.appendSql(" where 1=1 ");
		  if(beginDate > 0){
		    sql.appendSql(" and belongs_date >= ").appendValue(beginDate);
		  }
		  if(endDate > 0){
			  sql.appendSql(" and belongs_date <= ").appendValue(endDate); 
		  }
                  sql.appendSql(" order by create_at desc");
		  return pagerService.pager(DailyGeneralSituation.class, sql, pageNo, pageSize);
	  }
          
          /**
           * 统计平均值
           * @param beginDate
           * @param endDate
           * @param pageNo
           * @param pageSize
           * @return 
           */
          public Map<String, Object> getAvgNum(int beginDate, int endDate, int pageNo, int pageSize) {
                  SqlBuilder pagerSql = new SqlBuilder();
                  pagerSql.appendSql(" select * from ac_club_daily_general_situation where 1=1 ");
		  if(beginDate > 0){
		    pagerSql.appendSql(" and belongs_date >= ").appendValue(beginDate);
		  }
		  if(endDate > 0){
			  pagerSql.appendSql(" and belongs_date <= ").appendValue(endDate); 
		  }
                  
                  SqlBuilder sql = new SqlBuilder();
		  sql.appendSql(" SELECT FLOOR(AVG(visitor_count)) visitorCountAvg, FLOOR(AVG(topic_count)) topicCountAvg,FLOOR(AVG(comment_count)) commentCountAvg, ")
                          .appendSql(" FLOOR(AVG(comment_reply_count)) commentReplyCountAvg,FLOOR(AVG(topic_reply_count)) topicReplyCountAvg, ")
                          .appendSql(" FLOOR(AVG(praise_count)) praiseCountAvg FROM (")
                          .appendSql(pagerSql.getSql()).appendSql(" ) a");
                  
                  JdbcTemplate jdbc = geliDao.getJdbcTemplate();
                  Map<String, Object> map = jdbc.queryForMap(sql.getSql(), pagerSql.getValues());
                  return map;
          }
}
